<?php


namespace app\controller\web;


use app\model\exam\Record;
use think\facade\Config;

/**
 * @ApiInternal ()
 */
class Exam extends Common
{

    //允许考试次数
    const USE_EXAM_NUM = 9;

    protected $model;
    protected $examPaperModel;
    protected $paperQuestionModel;


    protected function _initialize()
    {
        $this->model = new \app\model\Exam();
        $this->examPaperModel = new \app\model\exam\Papers();
        $this->paperQuestionModel = new \app\model\exam\PaperQuestions();
    }

    public function list()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 4);

        $userInfo = $this->getLoginUserInfo();
        $result = $this->model->where('status', '=', 1)
            ->where('start_time', '>=', time())
            ->whereRaw("FIND_IN_SET('{$userInfo["org_id"]}', allow_org_ids)")
            ->paginate($pageSize)->toArray();

        if (!$result)
            return $this->error('数据获取失败');

        $org = \app\model\Org::where('status', '=', 1)->column('name', 'id');
        foreach ($result['data'] as &$row)
        {
            $row['allow_orgs'] = '';
            $orgIds = explode(',', $row['allow_org_ids']);
            foreach ($orgIds as $v){
                if (!isset($org)) continue;
                $row['allow_orgs'] .= $org[$v] . '，';
            }
            $row['allow_orgs'] = rtrim($row['allow_orgs'], '，');
        }
        return $this->success('数据获取成功', $result);

    }

    public function setExamBtnStatus()
    {
        $examId = (int)$this->request->post('exam_id' , 0);
        $userId = $this->getLoginUserInfo()['id'];

        $examRecord = Record::where('exam_id', $examId)
            ->where('student_id', $userId)
            ->order('id', 'desc')
            ->value('num');

        $data = [
            'use_exam' => $examRecord >= self::USE_EXAM_NUM ? 0 : 1
        ];
        return $this->success('seccess', $data);


    }

    public function paperInfo()
    {

        $examId = (int)$this->request->get('examId' , 0);
        $paperId = (int)$this->request->get('paperId' , 0);
        if ($paperId <= 0) {
            return $this->error('试卷Id参数错误'.$paperId);
        }

        #查询试卷的信息
        $paperInfo = $this->examPaperModel->where('id', $paperId)->find();
        if (!$paperInfo) {
            return $this->error('试卷数据获取失败');
        }

        $questionPaper = $this->paperQuestionModel->where('paper_id',  $paperId)
            ->field('id, question_id, score, sort')
            ->order('sort', 'asc')
            ->select()
            ->toArray();

        $questionIds = array_column($questionPaper, 'question_id');
//        $questionPaper = array_column($questionPaper, Null, 'question_id');


        $questionList = \app\model\Questions::where('id', 'in', $questionIds)
            ->field('*')->order('id', 'asc')->select()->toArray();

        $data = [];
        if (empty($questionList)) {
            return $this->success('数据获取成功', $data);

        }

        foreach ($questionList as $row)
        {
            $options = [
                $row['option_a'], $row['option_b']
            ];
            if (!empty($row['option_c'])) {
                array_push($options, $row['option_c']);
            }
            if (!empty($row['option_d'])) {
                array_push($options, $row['option_d']);
            }
            if (!empty($row['option_e'])) {
                array_push($options, $row['option_e']);
            }
            if (!empty($row['option_f'])) {
                array_push($options, $row['option_f']);
            }

            $data[] = [
                'id' => $row['id'],
                'type' => $this->getQuestionTypeStr($row['type']),
                'title' => $row['title'],
                'options' => $options,
                'answer' => $this->fmtAnwser($row['anwser'], $row['type']),
                'analysis' => $row['analysis'],
                'score' => $row['score'],

            ];
        }

        $examInfo = $this->model->where('id', $examId)->find();
        return $this->success('数据获取成功', ['questions' => $data, 'paperInfo' => $paperInfo, 'examInfo' => $examInfo]);
    }

    public function yuePaper()
    {
        $data = $this->request->post();
        $paperId = $data['paperId'];
        $examId = $data['examId'];
        $answers = $data['answers'];
        if (empty($paperId) ||empty($examId)) {
            return $this->error('参数错误');
        }
        $uId = $this->getLoginUserInfo()['id'];
        $recordModel = new Record();
        $examNum = $recordModel->where('exam_id', $examId)->where('papers_id', $paperId)
            ->where('student_id', $uId)->order('id', 'desc')->value('num');
        if (is_numeric($examNum) && $examNum >= self::USE_EXAM_NUM) {
            return $this->error('您已参加过此次考试，请勿重复提交');
        }

        $paperQuestionIds = $this->paperQuestionModel->where('paper_id', $paperId)->column('question_id');
        $questions = \app\model\Questions::where('id', 'in', $paperQuestionIds)
            ->column('id, type, anwser, score', 'id');

        if (empty($questions)) {
            return $this->error('试题未查询到');
        }
        $data = [
            'score' => 0,
            'result' => [],
        ];
        foreach ($questions as $val) {
            $isTure = 2;
            $data['result'][$val['id']] = false;
            $score = $val['score'];
            if ($val['score'] <= 0) {
                switch ($val['type']) {
                    case 1:
                    case 2:
                    case 3:
                        $score = 2;
                        break;
                    case 4:
                        $score = 10;
                        break;
                    case 5:
                        $score = 5;
                        break;
                }
            }
            if (empty(array_diff($this->fmtAnwser($val['anwser'], $val['type']), $answers[$val['id']] ?? []))) {
                $data['score'] += $score;
                $isTure = 1;
                $data['result'][$val['id']] = true;
            }
            //todo
            $userAnwser = $answers[$val['id']] ?? [];
            $recoedData[] = [
                'exam_id' => $examId,
                'papers_id' => $paperId,
                'question_id' => $val['id'],
                'student_id' => $uId,
                'answer' => rtrim($this->fmtAnwser2($userAnwser, $val['type']), ','),
                'type' => $val['type'],
                'is_right' => $isTure ,
                'score' => $val['score'] > 0 ? $val['score'] : 2,
                'num'   => is_numeric($examNum) ? $examNum + 1 : 1,
            ];

        }

        $result = $recordModel->saveAll($recoedData);
        return $this->success('数据获取成功', $data);

    }

    public function getExamRecordList()
    {
        $uId = $this->getLoginUserInfo()['id'];
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('page_size', 10);
        $recordModel = new Record();


        $result = $recordModel->where('student_id', $uId)->order('id', 'desc')
            ->field('exam_id, papers_id, num, create_time')->group('exam_id, papers_id, num')
            ->paginate($pageSize)->toArray();

        $ids = [];
        foreach ($result['data'] as $val) {
            $ids[] = $val['exam_id'];
        }
        $examList = $this->model->where('id', 'in', $ids)->column('name', 'id');

        $ret = $recordModel->where('student_id', $uId)->where('is_right', 1)->where('exam_id', 'in', $ids)
            ->field('sum(score) as score, exam_id, papers_id, num')->group('exam_id, papers_id, num')->select()->toArray();

        foreach ($result['data']  as &$val)
        {
            $val['score'] = 0;
            $val['exam_name'] = $examList[$val['exam_id']] ?? '';

            foreach ($ret as $val2)
            {
                if ($val['exam_id'] == $val2['exam_id'] && $val['papers_id'] == $val2['papers_id'] && $val['num'] == $val2['num'])
                {
                    $val['score'] = $val2['score'];
                } else {
                    continue;
                }

            }
        }

        return $this->success('数据获取成功', $result);
    }



    private function fmtAnwser($anwser, $type = 1)
    {
        $options = [
            'A' => 0,
            'B' => 1,
            'C' => 2,
            'D' => 3,
            'E' => 4,
            'F' => 5,
        ];
        if ($type == 4) return explode(',', $anwser);
        if ($type == 5) return $anwser;

        $res = [];
        if (empty($anwser)) return $res;

        $anwser = explode(',', $anwser);
        foreach ($anwser as $v)
        {
            $res[] = $options[$v] ?? $v;
        }
        return $res;
    }

    private function fmtAnwser2($anwser, $type = 1)
    {
        $options = [
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
        ];

        if ($type == 4) {
            return $anwser[0];
        }

        if ($type == 5) {
            return explode('</br>', $anwser);
        }

        $res = '';
        if (empty($anwser)) return $res;

        foreach ($anwser as $v)
        {
            $res .= isset($options[$v]) ? $options[$v] . ',' : $v;
        }
        return $res;
    }

}
